<?php

namespace App\Http\Controllers\Client\Common;

use App\Http\Controllers\RootController as Controller;
use App\Services\Sms\CaptchaService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;

class SendSmsCaptchaController extends Controller
{
    public function handle(Request $request)
    {
        $param['mobile'] = $request->post('mobile', '');
        $rules    = [
            'mobile' => 'required',
        ];
        $messages = [
            'mobile.required' => '请输入手机号',
        ];

        $validator = Validator::make($param, $rules, $messages);

        if ($validator->fails())
        {
            return $this->failure($validator->errors()->first(), 'VALIDATION_FAIL');
        }

        // 创建验证码
        $code = rand(1000, 9999);

        // 检查是否在保护期内
        if (CaptchaService::has($param['mobile']))
        {
            return $this->failure('请求太快了', 'E_BUSY');
        }

        // 发送
        try
        {
            CaptchaService::sendCode($param['mobile'], $code, '', 4);

        }
        catch (\Exception $e)
        {
            return $this->failure((env('APP_DEBUG') ? $e->getMessage() : '短信发送失败'), 'SEND_FAIL');
        }

        // 总是返回成功
        return $this->success();
    }
}
